package org.fast.easy.auth.util;

import cn.hutool.core.collection.CollUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.fast.easy.auth.domain.vo.LoginTenantVo;
import org.fast.easy.auth.domain.vo.TenantListVo;
import org.fast.easy.core.util.MapstructUtils;
import org.fast.easy.core.util.StreamUtils;
import org.fast.easy.core.util.StringUtils;
import org.fast.easy.framework.tenant.helper.TenantHelper;
import org.fast.easy.system.upms.domain.vo.SysTenantVo;

import java.net.URL;
import java.util.List;

/**
 * 类说明
 *
 * @author YanMing
 * @date 2024/5/29
 */
public class LoginTenantUtil {

    public static LoginTenantVo getLoginTenantVo(HttpServletRequest request, List<SysTenantVo> tenantList) throws Exception{
        List<TenantListVo> voList = MapstructUtils.convert(tenantList, TenantListVo.class);
        // 获取域名
        String host;
        String referer = request.getHeader("referer");
        if (StringUtils.isNotBlank(referer)) {
            // 这里从referer中取值是为了本地使用hosts添加虚拟域名，方便本地环境调试
            host = referer.split("//")[1].split("/")[0];
        } else {
            host = new URL(request.getRequestURL().toString()).getHost();
        }
        // 根据域名进行筛选
        List<TenantListVo> list = StreamUtils.filter(voList, vo ->
                StringUtils.equals(vo.getDomain(), host));
        // 返回对象
        LoginTenantVo vo = new LoginTenantVo();
        vo.setVoList(CollUtil.isNotEmpty(list) ? list : voList);
        vo.setTenantEnabled(TenantHelper.isEnable());
        return vo;
    }

}
